package cn.caplike.demo.repository.java;

import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;

/**
 * Description: 文件操作相关
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-10-07 14:56
 */
public class AboutFile {

    public static void main(String[] args) {

        final String encodedData = store();
        System.out.println("encodedData: " + encodedData);

        // ~ 读取文件到内存并写入成另外一个文件
        write(encodedData);
    }

    @SneakyThrows
    public static String store() {
        String path = Objects.requireNonNull(AboutFile.class.getClassLoader().getResource("userkey/1521449951.p12")).getPath();
        if (path.startsWith("/"))
            path = path.substring(1);

        final File resourcesFile = new File(path);

        try (
                final FileInputStream fileInputStream = new FileInputStream(resourcesFile)
        ) {

            final String encodedData = new String(Base64.getEncoder().encode(IOUtils.toByteArray(fileInputStream)), StandardCharsets.UTF_8);
            System.out.println(encodedData);
            return new String(IOUtils.toByteArray(fileInputStream), StandardCharsets.UTF_8);
        }
    }

    @SneakyThrows
    public static void write(final String encodedData) {
        String path = Objects.requireNonNull(AboutFile.class.getClassLoader().getResource("userkey")).getPath();
        if (path.startsWith(File.separator))
            path = path.substring(1);

        System.out.println(path);

        final byte[] decodeData = Base64.getDecoder().decode(encodedData);
        try (
                final FileOutputStream fileOutputStream = new FileOutputStream(path + File.separator + "temp.p12")
        ) {
            fileOutputStream.write(decodeData);
        }
    }

}
